package ua.yandex.collections;

import java.util.Comparator;

public class MyCollections {

    static void reverse(MyList list) {
        Object[] arr = list.toArray();
        list.clear();
        System.out.print(arr[0]);
        for (int i = 0; i < arr.length; i++) {
            list.add(0, arr[i]);
        }
    }

    //Реализует рекурсивный поиск в отсортированном массиве методом бисекции.
    static int binarySearch(MyList list, Object key) {
        Object[] temporary = list.toArray();
        int size = list.size();
        int left = 0;
        int right = size - 1;
        int medium = (left + right) / 2;
        while (left != medium && right != medium) {
            if (((Comparable) temporary[medium]).compareTo(key) < 0) {
                left = medium;
                medium = (left + right) / 2;
            } else if (((Comparable) temporary[medium]).compareTo(key) > 0) {
                right = medium;
                medium = (left + right) / 2;
            } else {
                return medium;

            }
        }
        return -medium - 1;
    }

    //Реализует рекурсивный поиск в отсортированном массиве методом бисекции.
    public static int binarySearch(MyList list, Object key, Comparator cp) {
        Object[] temporary = list.toArray();
        int size = list.size();
        int left = 0;
        int right = size - 1;
        int medium = (left + right) / 2;
        while (left != medium && right != medium) {
            if (cp.compare(temporary[medium], key) < 0) {
                left = medium;
                medium = (left + right) / 2;
            } else if (cp.compare(temporary[medium], key) > 0) {
                right = medium;
                medium = (left + right) / 2;
            } else {
                return medium;

            }
        }
        return -medium - 1;
    }
}
